import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class Test01 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);

        //1.创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource(); //向上转型
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");  //再将父类转成子类类型
        ((MysqlDataSource)dataSource).setUser("root"); //设置用户名
        ((MysqlDataSource)dataSource).setPassword("jzh020829");   //设置密码
        //2.和数据库服务器建立连接
        Connection connection = dataSource.getConnection();

        //3.从控制台读取用户输入的内容
        System.out.println("请输入学生姓名:");
        String name = scanner.next();
        System.out.println("请输入学号:");
        int id = scanner.nextInt();

        //4.构建sql语句

        String sql = "insert into student value (?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);//提前预编译sql语句
        statement.setInt(1,id); //把第一个？替换成id
        statement.setString(2,name); //把第二个？替换成name
        //打印需要加到拼接数据之后
        System.out.println(statement);

        //5.执行sql语句
        int ret = statement.executeUpdate();//将预编译的语句给服务器做出相应
        System.out.println("ret = "+ret);

        //6.释放必要的资源
        statement.close();
        connection.close();




    }
}
